package cn.fzc.yipai.service.impl;

import cn.fzc.yipai.entity.Account;
import cn.fzc.yipai.mapper.AccountMapper;
import cn.fzc.yipai.service.AccountService;
import cn.fzc.yipai.service.LoginService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyh
 * @since 2021-07-17
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    LoginService loginService;

    @Override
    public void login(String account) {

        //查询用户信息
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        Account one = this.getOne(queryWrapper);

        if (one != null) {
            //check Login
            if (StringUtils.isNotBlank(one.getToken())) {
                if (loginService.checkLogin(one.getToken())) {
                    log.info("[{}],存在token并且已登录", account);
                    return;
                }
            }
            log.info("[{}],不存在token尝试登录", account);

            String accessToken = loginService.login(one.getAccount(), one.getPassword());
            if (StringUtils.isNotBlank(accessToken)) {
                log.info("[{}],登录成功, 更新token", account);
                one.setUpdateTime(new Date());
                one.setToken(accessToken);
                this.updateById(one);
            }
        }

    }

    @Override
    public List<Account> getLoginList() {
        //获取所有账号
        List<Account> list = list();
        for (Account account : list) {
            login(account.getAccount());
        }
        return list();
    }

}
